from sqlalchemy import Column, Integer, String, ForeignKey, Table, DECIMAL

"""

You can use the extra Flask-AppBuilder fields and Mixin's

AuditMixin will add automatic timestamp of created and modified by who


"""
from sqlalchemy import Date
from flask_appbuilder.security.sqla.models import User

import datetime
from sqlalchemy.orm import relationship
from flask_appbuilder import Model


class Department(Model):
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True, nullable=False)

    def __repr__(self):
        return self.name


def today():
    return datetime.datetime.today().strftime('%Y-%m-%d')


class Company(Model):
    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique=True, nullable=False)

    def __repr__(self):
        return self.name


class MyUser(User):
    __tablename__ = 'ab_user'
    extra = Column(String(256))
    company_id = Column(Integer, ForeignKey("company.id"), nullable=True)
    company = relationship("Company")
    department_id = Column(Integer, ForeignKey('department.id'), nullable=True)
    department = relationship("Department")


from flask_appbuilder.models.mixins import AuditMixin

assoc_user_eventgroup = Table('eventgroup_user',
                              Model.metadata,
                              Column('id', Integer, primary_key=True),
                              Column('user_id', Integer, ForeignKey(MyUser.id)),
                              Column('eventgroup_id', Integer, ForeignKey("event_group.id")))


class EventGroup(AuditMixin,Model):
    id = Column(Integer, primary_key=True)
    date = Column(Date, default=today)
    title = Column(String(100), default='')
    users = relationship('MyUser',
                         secondary=assoc_user_eventgroup,
                         backref='event_group')


class Event(AuditMixin, Model):
    id = Column(Integer, primary_key=True)
    amount = Column(DECIMAL(10, 2), default=0)
    date = Column(Date, default=today)
    description = Column(String(100), default='')
    group_id = Column(Integer, ForeignKey(EventGroup.id), nullable=False)
    group = relationship("EventGroup")
    def participant_facts(self):
        pns = ""
        for p in self.participant:
            pns = pns+p.user_name()+' 用'+str(int(p.spend_share))+' 付'+str(p.pay)+', '
        return pns

class Participant(AuditMixin, Model):
    id = Column(Integer, primary_key=True)
    event_id = Column(Integer, ForeignKey('event.id'), nullable=False)
    event = relationship("Event",backref="participant")
    spend_share = Column(DECIMAL(10, 2))
    spend = Column(DECIMAL(10, 2), default=0)
    pay = Column(DECIMAL(10, 2))
    user_id = Column(Integer, ForeignKey(MyUser.id), nullable=False)
    user = relationship("MyUser", primaryjoin="Participant.user_id == MyUser.id")
    balance = Column(DECIMAL(10, 2), default=0)
    def user_name(self):
        return self.user.last_name+self.user.first_name